<template>
  <view class="replenish">
    <u-list @scrolltolower="handleScrolltolower">
      <view class="p-20">
        <template v-if="list.length">
          <u-list-item v-for="(item, index) in list" :key="index" class="mb-20">
            <my-goods :data="item"></my-goods>
          </u-list-item>
        </template>
        <template v-else>
          <my-empty text="暂无数据"></my-empty>
        </template>
      </view>
    </u-list>
    <my-tabbar current-page="/pages/index/replenish"></my-tabbar>
  </view>
</template>

<script setup>
import { onReady } from "@dcloudio/uni-app";
import { reactive, ref } from "vue";
import { useStore } from "vuex";

/**
 * 使用 Vuex store
 * @type {Object}
 */
const store = useStore();

/**
 * 请求参数
 * @type {Object}
 * @property {number} page - 当前页码
 * @property {number} size - 每页数据条数
 */
const params = reactive({
  page: 1,
  size: 10,
});

/**
 * 订单历史列表
 * @type {Array}
 */
const list = ref([]);

/**
 * 总页数
 * @type {Ref<number>}
 */
const totalPage = ref(0);

/**
 * 处理滚动到底部事件
 */
function handleScrolltolower() {
  if (params.page < totalPage.value) {
    params.page += 1;
    getData(false);
  }
}

/**
 * 获取订单历史数据
 * @param {boolean} [isCover=true] - 是否覆盖原有数据
 * @returns {Promise} 获取数据的 Promise
 */
async function getData(isCover = true) {
  try {
    uni.showLoading({ title: "加载中..." });
    const response = await store.dispatch("fetchOrderHistory", params);
    uni.hideLoading();
    if (response) {
      totalPage.value = response.total_page;
      if (isCover) {
        list.value = response.records;
      } else {
        list.value = list.value.concat(response.records);
      }
    }
  } catch (err) {
    uni.hideLoading();
    console.log("发送请求失败", err);
  }
}

/**
 * 在页面准备好时调用 getData 函数
 */
onReady(() => {
  getData();
});
</script>

<style lang="scss" scoped></style>
